package com.Flucard_IT;

import java.util.List;

import utils.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import define.Constants;

public class Settings extends Activity {
	/**
	 * String section
	 */
	private String[] LISTS, TIME_VALUES;

	private final String TAG = Settings.class.getSimpleName();

	/**
	 * Data section
	 */
	private ArrayAdapter<String> mAaDisplayTimeAdapter;

	/**
	 * Handler section
	 */

	/**
	 * View section
	 */
	private AlertDialog.Builder mAdConfirm;
	private AlertDialog.Builder mAdExit;
	private CheckBox mCbEnableSlideShowMode;
	private EditText mEtSpecifyFolder;
	private List<ScanResult> mListScanResult;
	private Spinner mSpinnerDisplayTime;

	/**
	 * The others section
	 */
	private SharedPreferences mSp;
	private SharedPreferences.Editor mSpEditor;
	private WifiManager mWifiManager;

	/**
	 * On Click
	 * 
	 * @param v
	 */
	public void onClickSettings(View v) {
		switch (v.getId()) {
		case R.id.btn_save:
			mAdConfirm.show();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_settings);

		// Initialize
		initialDialog();
		initialVariables();

		// Get shared preference
		mSp = getSharedPreferences(Constants.SHARED_PREFERENCE_NAME,
				Context.MODE_PRIVATE);
		mSpEditor = mSp.edit();

		define.Settings.TIME_INTERVAL = Integer.valueOf(mSp.getString(
				Constants.SHARED_PREFERENCE_KEY_TIME_INTERVAL,
				define.Settings.TIME_INTERVAL + ""));

		mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

		// Initialize data
		initialData();

		/**
		 * Scan wireless and get the wifi list
		 */
		// Begin scan wireless
		mWifiManager.startScan();
		// Get results
		mListScanResult = mWifiManager.getScanResults();
		LISTS = new String[mListScanResult.size() + 1];
		TIME_VALUES = new String[10];

		/**
		 * Get stored folder name
		 */
		if (mSp.getString(Constants.SHARED_PREFERENCE_KEY_FOLDER, "")
				.compareTo("") == 0) {
			mEtSpecifyFolder.setText(getString(R.string.default_folder));
		} else {
			mEtSpecifyFolder.setText(mSp.getString(
					Constants.SHARED_PREFERENCE_KEY_FOLDER, ""));
		}

		for (int a = 0; a < mListScanResult.size(); a++) {
			LISTS[a + 1] = mListScanResult.get(a).SSID;
		}

		for (int b = 1; b < 11; b++) {
			TIME_VALUES[b - 1] = "" + b + "";
		}

		// Initialize adapter to set to Spinner
		initialAdapter();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			mAdExit.show();
		}

		return super.onKeyDown(keyCode, event);
	}

	/**
	 * Initial methods
	 */

	private void initialAdapter() {
		mAaDisplayTimeAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, TIME_VALUES);
		mAaDisplayTimeAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		mSpinnerDisplayTime.setAdapter(mAaDisplayTimeAdapter);
		mSpinnerDisplayTime.setSelection(define.Settings.TIME_INTERVAL - 1);
	}

	private void initialData() {
		String SLIDE_MODE = mSp.getString(
				Constants.SHARED_PREFERENCE_KEY_SLIDESHOW_MODE, "no");
		if (SLIDE_MODE.compareTo("yes") == 0) {
			mCbEnableSlideShowMode.setChecked(true);
		} else {
			mCbEnableSlideShowMode.setChecked(false);
		}

		mSpinnerDisplayTime
				.setOnItemSelectedListener(new OnItemSelectedListener() {
					@Override
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						define.Settings.TIME_INTERVAL = Integer.valueOf(parent
								.getItemAtPosition(pos).toString());
					}

					@Override
					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
	}

	private void initialDialog() {
		mAdConfirm = new AlertDialog.Builder(this)
				.setCancelable(true)
				.setMessage(
						getString(R.string.reconnect_app_after_settings_take_effect))
				.setPositiveButton(getString(R.string.ok),
						new OnClickListener() {
							@Override
							public void onClick(DialogInterface d,
									int whichButton) {
								/**
								 * Save new Settings
								 */
								saveIntoSharedPreferences();

								/**
								 * Restart Application to apply new effect
								 */
								Utils.restartApplication(Settings.this,
										SplashScreen.mContext);

								// Finish current application
								android.os.Process
										.killProcess(android.os.Process.myPid());
							}
						})
				.setNegativeButton(getString(R.string.cancel),
						new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								/**
								 * Return Home page
								 */
								finish();
								startActivity(new Intent(Settings.this,
										Home.class));
							}
						});

		mAdExit = new AlertDialog.Builder(this)
				.setTitle(R.string.title_exit)
				.setIcon(R.drawable.ic_info)
				.setCancelable(false)
				.setMessage(R.string.content_exit)
				.setPositiveButton(R.string.ok, new OnClickListener() {
					@Override
					public void onClick(DialogInterface d, int whichButton) {
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				})
				.setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog9,
									int whichButton) {
							}
						});
	}

	private void initialVariables() {
		mCbEnableSlideShowMode = (CheckBox) findViewById(R.id.cb_enable_slide_show_mode);
		mEtSpecifyFolder = (EditText) findViewById(R.id.et_specify_folder);
		mSpinnerDisplayTime = (Spinner) findViewById(R.id.spinner_display_time);
	}

	/**
	 * Basic methods
	 */
	private void saveIntoSharedPreferences() {
		/**
		 * Save into Shared Preference
		 */
		mSpEditor.putString(Constants.SHARED_PREFERENCE_KEY_FOLDER,
				mEtSpecifyFolder.getText().toString());
		mSpEditor.putString(Constants.SHARED_PREFERENCE_KEY_TIME_INTERVAL,
				define.Settings.TIME_INTERVAL + "");

		if (mCbEnableSlideShowMode.isChecked()) {
			mSpEditor.putString(Constants.SHARED_PREFERENCE_KEY_SLIDESHOW_MODE,
					"yes");
		} else {
			mSpEditor.putString(Constants.SHARED_PREFERENCE_KEY_SLIDESHOW_MODE,
					"no");
		}
		mSpEditor.commit();
	}
}
